package helper

import (
	"context"
	"errors"
	"fmt"
	"runtime"
)

// Try 协程中执行的时候捕获异常
func Try(ctx context.Context, try func(ctx context.Context)) (err error) {
	if try == nil {
		return
	}
	defer func() {
		if exception := recover(); exception != nil {
			if v, ok := exception.(error); ok {
				err = v
			} else {
				if _, file, line, ok := runtime.Caller(2); ok {
					err = errors.New(fmt.Sprintf("在%s的第[%d]行出现错误：\n %+v", file, line, exception))
				} else {
					err = errors.New("异常：协程中出现异常")
				}
			}
		}
	}()
	try(ctx)
	return
}
